<template>
  <div class="roles">
    <BreadCrumb :item="['权限管理', '角色列表']"></BreadCrumb>
    <!-- 主体 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-button type="primary" @click="showDialog('add')"
          >添加角色</el-button
        >
      </div>
      <!-- 表格 -->
      <el-table :data="rolesList" style="width: 100%" border :stripe="true">
        <el-table-column type="expand" width="48px">
          <template slot-scope="props">
            <!--  -->
            <el-row
              v-for="item in props.row.children"
              :key="item.id"
              class="vcenter"
            >
              <el-col :span="6"
                ><span class="box"
                  >{{ item.authName }}
                  <i
                    class="el-icon-close"
                    @click="removeRolesRoot(props.row.id, item.id)"
                  ></i></span
                ><i class="el-icon-caret-right"></i
              ></el-col>
              <el-col :span="18" class="el-element">
                <el-row
                  v-for="element in item.children"
                  :key="element.id"
                  class="vcenter"
                >
                  <el-col :span="8"
                    ><span class="box box1"
                      >{{ element.authName
                      }}<i
                        class="el-icon-close"
                        @click="removeRolesRoot(props.row.id, element.id)"
                      ></i></span
                    ><i class="el-icon-caret-right"></i
                  ></el-col>
                  <el-col :span="16"
                    ><span
                      v-for="el in element.children"
                      :key="el.id"
                      class="box box2"
                      >{{ el.authName
                      }}<i
                        class="el-icon-close"
                        @click="removeRolesRoot(props.row.id, el.id)"
                      ></i></span
                  ></el-col>
                </el-row>
              </el-col>
            </el-row>
            <!--  -->
          </template>
        </el-table-column>
        <el-table-column width="48px" type="index"> </el-table-column>
        <el-table-column label="角色名称" prop="roleName"> </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
        <el-table-column label="操作" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showDialog('edit', row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeRoles(row)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-star-off"
              size="mini"
              @click="showDialog('allot', row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 弹层 -->
    <!-- 弹出层 -->
    <el-dialog
      :title="typeTitle"
      :visible.sync="dialogFormVisible"
      @close="handleClose"
    >
      <!-- 分配权限 -->
      <div v-if="type === 'allot'">
        <el-tree
          ref="tree"
          :data="rolesTree"
          show-checkbox
          node-key="id"
          :props="defaultProps"
          :default-expanded-keys="expanded"
          :default-checked-keys="checked"
        >
        </el-tree>
      </div>
      <!-- 添加表单 -->
      <el-form v-else ref="form" :model="form" :rules="rules">
        <el-form-item label="角色名称" label-width="80px" prop="roleName">
          <el-input v-model="form.roleName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" label-width="80px" prop="roleDesc">
          <el-input v-model="form.roleDesc" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleRoles">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getRolesList } from '@/api/menu'
import {
  addRoles,
  allotRolesRoot,
  delRoles,
  delRolesRoot,
  editRoles,
  getRolesDetail,
  getRolesTree,
} from '@/api/role'
import { Message } from 'element-ui'
const mapRoles = {
  add: '添加角色',
  edit: '编辑角色',
  allot: '分配权限',
}
export default {
  name: 'Roles',
  data() {
    return {
      rolesList: [],
      rolesTree: [],
      expanded: [],
      checked: [],
      defaultProps: {
        children: 'children',
        label: 'authName',
      },
      form: {
        roleName: '',
        roleDesc: '',
      },
      type: 'add',
      dialogFormVisible: false,
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        roleDesc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },
        ],
      },
    }
  },
  methods: {
    async initRolesList() {
      const res = await getRolesList()
      // console.log(res.data)
      this.rolesList = res.data
    },
    async showDialog(type, row) {
      this.type = type
      // 获取当前角色信息
      if (type === 'edit') {
        const res = await getRolesDetail(row.id)
        // console.log(res)
        this.form = { ...res.data }
      }
      if (type === 'allot') {
        this.form.id = row.id
        const res = await getRolesTree()
        // console.log(res)
        this.rolesTree = res.data
        // 选中节点设置
        const currentRoles = this.rolesList.filter(
          (item) => item.id === row.id
        )[0]
        this.handleRolesId(currentRoles)
      }
      this.dialogFormVisible = true
    },
    // 递归处理权限完成
    handleRolesId(node) {
      if (!node.children) {
        this.checked.push(node.id)
        return
      }
      node.children.forEach((item) => {
        this.expanded.push(item.id)
        this.handleRolesId(item)
      })
    },
    // 操作角色权限
    async handleRoles() {
      // 添加角色
      if (this.type === 'add') {
        await addRoles(this.form)
      }
      // 编辑角色
      if (this.type === 'edit') {
        await editRoles(this.form.roleId, {
          roleName: this.form.roleName,
          roleDesc: this.form.roleDesc,
        })
      }
      // 分配角色权限
      if (this.type === 'allot') {
        const rids = this.$refs.tree
          .getCheckedKeys()
          .concat(this.$refs.tree.getHalfCheckedKeys())
          .toString()
        await allotRolesRoot(this.form.id, { rids })
        Message('更新权限成功')
      }
      this.dialogFormVisible = false
      this.initRolesList()
    },
    // 删除角色
    async removeRoles(row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          await delRoles(row.id)
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
          this.initRolesList()
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    // 删除指定角色指定权限
    async removeRolesRoot(roleId, rightId) {
      this.$confirm('此操作将删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const res = await delRolesRoot(roleId, rightId)
          this.rolesList.find((item) => item.id === roleId).children = res.data
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
      // console.log(roleId)
      // console.log(rightId)
    },
    // 关闭弹层
    handleClose() {
      if (this.type !== 'allot') {
        this.$refs.form.resetFields()
      } else {
        this.expanded = []
        this.checked = []
      }
    },
  },
  computed: {
    typeTitle() {
      return mapRoles[this.type]
    },
  },
  created() {
    this.initRolesList()
  },
}
</script>

<style lang="less" scoped>
.inTable {
  padding: 20px;
}
/deep/ .el-table__cell.el-table__expanded-cell {
  padding: 20px 50px;
  > :nth-child(1) {
    border-top: 1px solid #eee;
  }
  > .el-row {
    border-bottom: 1px solid #eee;
  }
}
.el-element {
  > .el-row {
    border-bottom: 1px solid #eee;
  }
  > :last-child {
    border-bottom: none;
  }
}
.box {
  background-color: #ecf5ff;
  border-color: #d9ecff;
  display: inline-block;
  height: 32px;
  padding: 0 10px;
  line-height: 30px;
  font-size: 12px;
  color: #409eff;
  border-width: 1px;
  border-style: solid;
  border-radius: 4px;
  box-sizing: border-box;
  white-space: nowrap;
  margin: 6px 6px;
  &.box1 {
    background-color: #f0f9eb;
    border-color: #e1f3d8;
    color: #67c23a;
  }
  &.box2 {
    background-color: #fdf6ec;
    border-color: #faecd8;
    color: #e6a23c;
  }
}
/deep/ .vcenter {
  display: flex;
  align-items: center;
  overflow: hidden;
}
.el-icon-close {
  border-radius: 50%;
  text-align: center;
  position: relative;
  cursor: pointer;
  font-size: 12px;
  height: 16px;
  width: 16px;
  line-height: 16px;
  vertical-align: middle;
  top: -1px;
  right: -5px;
}
</style>
